package api

import (
	"context"
	"errors"
	"gdmin/global"
	"gdmin/model"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
	"github.com/cloudwego/hertz/pkg/route"
	"gorm.io/gorm"
)

// 健康检查
// @Summary 健康检查
// @Description 健康检查
// @Accept application/json
// @Produce application/json
// @Router /beat [get]
func beat(c context.Context, ctx *app.RequestContext) {
	hlog.Info("ping")

	ctx.JSON(consts.StatusOK, utils.H{"message": "pong"})
}

func BeatApi(r *route.RouterGroup) {
	r.GET("/beat", beat)
	r.GET("/hello", func(c context.Context, ctx *app.RequestContext) {

		err := global.DB.Transaction(func(tx *gorm.DB) error {
			var u = model.User{}
			u.Name = "测试"
			err2 := global.DB.Transaction(func(tx *gorm.DB) error {

				var u2 = model.User{}
				u2.Name = "测试2"

				tx.Save(&u2)
				//global.DB.Save(&u2)

				return errors.New("a;?")
			})
			// 一定要处理这个异常
			if err2 != nil {
				return err2
			}

			err2 = tx.Transaction(func(tx *gorm.DB) error {

				var u2 = model.User{}
				u2.Name = "测试3"

				tx.Save(&u2)
				return nil
			})

			if err2 != nil {
				return err2
			}

			return tx.Save(&u).Error

		})
		if err != nil {
			hlog.Error(err)
			return
		}

	})

}
